//
//  LGWeb.m
//  UniverseProject
//
//  Created by king on 2018/11/23.
//  Copyright © 2018年 Cloud2209. All rights reserved.
//

#import "XLWeakScriptMessageDelegate.h"
#import "LGWeb.h"

@interface LGWeb()<WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler>



@end


@implementation LGWeb

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        // 设置偏好设置
        config.preferences = [[WKPreferences alloc] init];
        // 默认为0
//        config.preferences.minimumFontSize = 14;
        // 默认认为YES
        config.preferences.javaScriptEnabled = YES;
        // 在iOS上默认为NO，表示不能自动通过窗口打开
        config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
        // web内容处理池
        config.processPool = [[WKProcessPool alloc] init];
        
        WKUserContentController *wkUController = [[WKUserContentController alloc] init];

        // 通过JS与webview内容交互
        config.userContentController = wkUController;
        // 注入JS对象名称AppModel，当JS通过AppModel来调用时，
        // 我们可以在WKScriptMessageHandler代理中接收到
        [config.userContentController addScriptMessageHandler:[[XLWeakScriptMessageDelegate alloc] initWithDelegate:self] name:@"IOSHeightCal"];

        self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height) configuration:config];
        self.webView.customUserAgent = @"ios";
        self.webView.navigationDelegate = self;
        self.webView.UIDelegate = self;
        //开了支持滑动返回
//        self.webView.allowsBackForwardNavigationGestures = YES;
        [self addSubview:self.webView];
    }
    return self;
}

- (void)setTarget_url:(NSString *)target_url{
    _target_url = target_url;
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:target_url?:@"http://www.blogcn.com/"]]];
}




- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:@"contentSize"]) {

        [self calHeight];
        
    }
}



// 页面开始加载时调用
-(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    
}
// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
    
}
// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{//这里修改导航栏的标题，动态改变
    typeof(self) weakSelf = self;

    
    //document.body.offsetHeight
    //document.body.scrollHeight
    
    [webView evaluateJavaScript:@"document.body.offsetHeight;" completionHandler:^(id _Nullable any, NSError * _Nullable error) {
        NSString *heightStr = [NSString stringWithFormat:@"%@",any];
        if ([weakSelf.webdelegate respondsToSelector:@selector(webView:LoadResult:webH:)]) {
            self.height = heightStr.floatValue;
            if (self.heightFix) {
                self.webView.size = CGSizeMake(self.width, heightStr.floatValue + 10);
            }
            [self.webdelegate webView:self.webView LoadResult:YES webH:heightStr.floatValue + 10];
        }
    }];
    
}

// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation{
    
}
// 接收到服务器跳转请求之后再执行
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{
    
}
// 在收到响应后，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
    
//    NSLog(@"%@",webView);
//    NSLog(@"%@",navigationResponse);
    
    WKNavigationResponsePolicy actionPolicy = WKNavigationResponsePolicyAllow;
    //这句是必须加上的，不然会异常
    decisionHandler(actionPolicy);
    
}
// 在发送请求之前，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    
//    self.title = webView.title;
    
    WKNavigationActionPolicy actionPolicy = WKNavigationActionPolicyAllow;
    
    
    if (navigationAction.navigationType==WKNavigationTypeBackForward) {//判断是返回类型
        
        //同时设置返回按钮和关闭按钮为导航栏左边的按钮 这里可以监听左滑返回事件，仿微信添加关闭按钮。
//        self.navigationItem.leftBarButtonItems = @[self.backBtn, self.closeBtn];
        //可以在这里找到指定的历史页面做跳转
        //        if (webView.backForwardList.backList.count>0) {                                  //得到栈里面的list
        //            NSLog(@"%@",webView.backForwardList.backList);
        //            NSLog(@"%@",webView.backForwardList.currentItem);
        //            WKBackForwardListItem * item = webView.backForwardList.currentItem;          //得到现在加载的list
        //            for (WKBackForwardListItem * backItem in webView.backForwardList.backList) { //循环遍历，得到你想退出到
        //                //添加判断条件
        //                [webView goToBackForwardListItem:[webView.backForwardList.backList firstObject]];
        //            }
        //        }
    }
    //这句是必须加上的，不然会异常
    decisionHandler(actionPolicy);
}

//显示一个JS的Alert（与JS交互）
//- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
//    NSLog(@"弹窗alert");
//    NSLog(@"%@",message);
//    NSLog(@"%@",frame);
//    [self.view makeToast:message];
//    completionHandler();
//}
//
////弹出一个输入框（与JS交互的）
//- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler{
//    NSLog(@"弹窗输入框");
//    NSLog(@"%@",prompt);
//    NSLog(@"%@",defaultText);
//    NSLog(@"%@",frame);
//
//    UIAlertController *alert = [UIAlertController alertControllerWithTitle:prompt message:defaultText preferredStyle:UIAlertControllerStyleAlert];
//    UIAlertAction *a1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//        //这里必须执行不然页面会加载不出来
//        completionHandler(@"");
//    }];
//    UIAlertAction *a2 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        NSLog(@"%@",
//             [alert.textFields firstObject].text);
//        completionHandler([alert.textFields firstObject].text);
//    }];
//    [alert addAction:a1];
//    [alert addAction:a2];
//    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
//        NSLog(@"%@",textField.text);
//    }];
//    [self presentViewController:alert animated:YES completion:nil];
//}
//
////显示一个确认框（JS的）
//- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler{
//    NSLog(@"弹窗确认框");
//    NSLog(@"%@",message);
//    NSLog(@"%@",frame);
//
//
//    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message message:nil preferredStyle:UIAlertControllerStyleAlert];
//    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//        completionHandler(NO);
//    }];
//    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
//        completionHandler(YES);
//    }];
//    [alertController addAction:cancelAction];
//    [alertController addAction:okAction];
//    [self presentViewController:alertController animated:YES completion:nil];
//}

- (void)calHeight{
    CGSize fittingSize = [_webView sizeThatFits:CGSizeZero];
    NSLog(@"%f",fittingSize.height);
    if ([self.webdelegate respondsToSelector:@selector(webView:LoadResult:webH:)]) {
        if (self.heightFix) {
            self.webView.height = fittingSize.height;
        }
        [self.webdelegate webView:self.webView LoadResult:YES webH:fittingSize.height];
    }
}

#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController
      didReceiveScriptMessage:(WKScriptMessage *)message {
    NSLog(@"%@", message.name);
    
//    if ([message.name isEqualToString:@"AppModel"]) {
//        // 打印所传过来的参数，只支持NSNumber, NSString, NSDate, NSArray,NSDictionary, and NSNull类型
//        NSLog(@"%@", message.body);
//        NSDictionary *dict = message.body;
////        [self getMessageHandler:dict];
//    }else if ([message.name isEqualToString:@"AppJump"]){
//        NSLog(@"%@", message.body);
//        NSDictionary *dict = message.body;
////        [self getMessagePush:dict];
//    }
}



- (void)avtivityLoadWithContent:(NSString *)content{
    
    

     NSString *htmls = [NSString stringWithFormat:@"<html> \n"
                            "<head> \n"
                            "<meta name=\"viewport\" content=\"width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no\" />"
                            "<style type=\"text/css\"> \n"
                            "body {font-size:15px;}\n"
                            "</style> \n"
                            "</head> \n"
                            "<body>"
                            "<script type='text/javascript'>"
                            "window.onload = function(){\n"
                            "var $img = document.getElementsByTagName('img');\n"
                            "for(var p in  $img){\n"
                            " $img[p].style.width = '100%%';\n"
                            "$img[p].style.height ='auto'\n"
                            "}\n"
                            "}"
                            "</script>%@"
                            "</body>"
                            "</html>", content];
    [self.webView loadHTMLString:htmls baseURL:nil];
}




@end
